import { PassportStrategy } from "@nestjs/passport";
import { Strategy, ExtractJwt } from "passport-jwt";
import { LoginService } from "../service/login.service";
import { HttpException, Injectable, Module } from "@nestjs/common";
import { ConfigModule, ConfigService } from "@nestjs/config";
import { Repository } from "typeorm";
import { UserEntity } from "../entity/user.entity";
import { InjectRepository } from "@nestjs/typeorm";

@Injectable()
@Module({
  imports: [ConfigModule]
})
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
    private readonly configService: ConfigService,
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: configService.get("JWT_SECRET")
    });
  }

  async validate(payload: any) {
    const user = await this.userRepository.findOne({
      where: {
        id: payload.uid
      }
    });
    if (!user) {
      throw new HttpException("用户不存在", 500);
    }
    return {
      uid: payload.uid,
      openid: payload.openid,
      user
    };
  }
}
